<?php

class WxMsgAction extends CommonAction
{
	public function index()
	{
		$where = '';
		$parameter = array();
		$uname = trim($_REQUEST['uname']);
		
		if(!empty($uname))
		{
			$this->assign("uname",$uname);
			$parameter['uname'] = $uname;
			$where.=" uname LIKE '%".mysqlLikeQuote($uname)."%' ";
		}
		
		$model = M('WxMsg');

		if(!empty($where))
		{
			$where = 'WHERE' . $where;
			$where = str_replace('WHERE AND','WHERE',$where);
		}

		$sql = 'SELECT COUNT(id) AS count 
			FROM '.C("DB_PREFIX").'wx_msg '.$where;
		
		$count = $model->query($sql);
		$count = $count[0]['count'];
		
		$sql = 'SELECT *  FROM '.C("DB_PREFIX").'wx_msg '.$where;
		$this->_sqlList($model,$sql,$count,$parameter,'id');
		
		$this->display ();
		return;
	}
	public function add(){
		$model = M('WxMsg');
		$data = $model->order('read_time desc')->find();
		if($data['read_time']<=0){
			$read_time = date("Ymd",strtotime("+1 day"));
			$data['read_time'] = strtotime($read_time);
		}	
		
		$list = $model->where("read_time='{$data['read_time']}'")->count();
		
		if($list<5){
			$read_time = $data['read_time'];
		}else{
			$read_time = $data['read_time']+(24*3600);
		}
		
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$pd = '';
		for($i=0;$i<6;$i++) 
		{
			$pd .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		$show_time = date('Ymd',$read_time);
		$tmp_time = date('Y-m-d',$read_time);
		$now_time = date('Ymd');
		if($now_time>=$show_time){
			$show_time = date('Ymd',time()+(24*3600));
			$tmp_time = date('Y-m-d',time()+(24*3600));
		}
		$first = '恭喜你购买成功！';	
		$keyword1 = '成功';	
		$keyword2 = date('Y-m-d H:i');
		$keyword3 = $show_time.$pd;
		$keyword5 = '微信支付';	
		$remark = '欢迎再次购买！';
		$turl = 'http://www.timenow.com.cn/w/turl.html?oid='.$keyword3;
		$this->assign('first',$first);
		$this->assign('keyword1',$keyword1);
		$this->assign('keyword2',$keyword2);
		$this->assign('keyword3',$keyword3);
		$this->assign('keyword5',$keyword5);
		$this->assign('read_time',$tmp_time);
		$this->assign('remark',$remark);
		$this->assign('turl',$turl);
		parent::add();
	}
	public function onlyadd(){
		parent::add();
	}
	public function insert(){
		$model = D ('WxMsg');
		$data = array();
		//$data['uname'] = $_POST['uname'];
		$data['openid'] = $_POST['openid'];
		$data['read_time'] = strtotime($_POST['read_time']);
		$data['send_time'] = time();
		$key4 = $_POST['keyword4'];
		$money_arr = array(1=>'360.00元',2=>'360.00元',3=>'200.00元',4=>'200.00元',5=>'360.00元');
		$data['money'] = $money_arr[$key4];
		
		$data['mtype'] = $key4;
		$msg_status = D('user')->where("email='{$_POST['openid']}'")->find();
		if($msg_status['uid']>0){
			$key3 = $_POST['keyword3'].$key4;
			$post_data = '{"touser":"'.$_POST['openid'].'","template_id":"cN3bejzWP6QvS5NK7c0BAanrI3gQN9mKLQTe9hn0lhQ","url":"'.$_POST['xurl'].'","topcolor":"#FF0000","data":{"first": {"value":"'.$_POST['first'].'", "color":"#173177"},"keyword1":{"value":"'.$_POST['keyword1'].'"},"keyword2": {"value":"'.$_POST['keyword2'].'"},"keyword3": {"value":"'.$key3.'"},"keyword4":{"value":"'.$data['money'].'"},"keyword5":{"value":"'.$_POST['keyword5'].'"},"remark":{"value":"'.$_POST['remark'].'", "color":"#173177"}}}';
			$data['content'] = $post_data;
			$data['grid'] = $key3;
			$data['uname'] = $msg_status['user_name'];
			
			$list=$model->data($data)->add();
			if (false !== $list)
			{
				$appid = 'wx5beb14a9ba033807';
				$secret='6c7f4e62f83d7e349f5e0234988270e3';
				$aurl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
				
				$access_token = json_decode(file_get_contents($aurl));
				$access_token=$access_token->access_token;
				
				$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
				
				$ch = curl_init();
				curl_setopt ($ch, CURLOPT_URL, $url);
				curl_setopt ($ch, CURLOPT_POST, 1);
				if($post_data != ''){
					curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
				}
				curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
				curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
				curl_setopt($ch, CURLOPT_HEADER, false);
				$results = curl_exec($ch);
				curl_close($ch);
				if($results['errcode']==0){					
					$this->assign('id',$list);
					$this->success ('消息发送成功');
				}else{
					$this->success ('消息发送失败');
				}			
			}else{
				//错误提示
				$this->saveLog(0);
				$this->error (L('ADD_ERROR'));
			}
		}else{
			//错误提示
			$this->saveLog(0);
			$this->error ('openid不存在');
		}		
	}
	public function onlyinsert(){
		$model = D ('WxMsg');
		$data = array();
		$data['uname'] = $_POST['uname'];
		$data['openid'] = $_POST['openid'];
		$data['read_time'] = strtotime($_POST['read_time']);
		$data['send_time'] = time();
		$key4 = $_POST['keyword4'];
		$money_arr = array(1=>'360.00元',2=>'360.00元',3=>'200.00元',4=>'200.00元',5=>'360.00元');
		$data['money'] = $money_arr[$key4];
		
		$data['mtype'] = $key4;
		$msg_status = D('user')->where("user_name='{$_POST['uname']}' and email='{$_POST['openid']}'")->find();
		if($msg_status['uid']>0){
			$key3 = $_POST['keyword3'].$key4;
			$post_data = '{"touser":"'.$_POST['openid'].'","template_id":"cN3bejzWP6QvS5NK7c0BAanrI3gQN9mKLQTe9hn0lhQ","url":"'.$_POST['xurl'].'","topcolor":"#FF0000","data":{"first": {"value":"", "color":"#173177"},"keyword1":{"value":""},"keyword2": {"value":"'.$_POST['keyword2'].'"},"keyword3": {"value":"'.$key3.'"},"keyword4":{"value":"'.$data['money'].'"},"keyword5":{"value":""},"remark":{"value":"", "color":"#173177"}}}';
			$data['content'] = $post_data;
			$data['grid'] = $key3;
			
			$list=$model->data($data)->add();
			if (false !== $list)
			{
				$this->assign('id',$list);
				$this->success ('添加消息成功');			
			}else{
				//错误提示
				$this->saveLog(0);
				$this->error (L('ADD_ERROR'));
			}
		}else{
			//错误提示
			$this->saveLog(0);
			$this->error ('用户名与openid不相符');
		}		
	}
	
	public function update()
	{
        $id = intval($_REQUEST['id']);
		$model = D ('WxMsg');
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}
		$data['read_time'] = strtotime($_POST['read_time']);
		//var_dump($_FILE); exit;
		// 更新数据
		$list=$model->save($data);
		if (false !== $list)
		{
			$this->saveLog(1,$id);
			$this->assign('jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		}
		else
		{
			//错误提示
			$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	public function outexcel(){
		require_once 'PHPExcel.php'; 
		include_once 'PHPExcel/Writer/Excel5.php';
		ini_set("memory_limit","200M");
		header("Content-Type: text/html; charset=utf8");
		 
		$objPHPExcel = new PHPExcel();

		// Add some data
		$objPHPExcel->setActiveSheetIndex(0);
		$model = M('WxMsg');
		$list = $model->order('read_time asc,id asc')->select();
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(50);
		$objPHPExcel->getActiveSheet()->SetCellValue('A1', '用户名');
		$objPHPExcel->getActiveSheet()->SetCellValue('B1', '类型');
		$objPHPExcel->getActiveSheet()->SetCellValue('C1', '预约时间');
		$objPHPExcel->getActiveSheet()->SetCellValue('D1', '金额');
		$objPHPExcel->getActiveSheet()->SetCellValue('E1', '详情');
		$objPHPExcel->getActiveSheet()->SetCellValue('F1', '是否已看');
		$objPHPExcel->getActiveSheet()->SetCellValue('G1', '是否已答');
		$objPHPExcel->getActiveSheet()->SetCellValue('H1', 'OPENID');
		
		$cates = array(1=>'职场',2=>'情感',3=>'亲子',4=>'老客户',5=>'个人');
		foreach($list as $k=>$v){
			$i=$k+2;
			$a = 'A'.$i;
			$b = 'B'.$i;
			$c = 'C'.$i;
			$d = 'D'.$i;
			$e = 'E'.$i;
			$f = 'F'.$i;
			$g = 'G'.$i;
			$h = 'H'.$i;
			if($v['is_read']==0){
				$read = '否';
			}else{
				$read = '是';
			}
			if($v['is_over']==0){
				$over = '否';
			}else{
				$over = '是';
			}
			$objPHPExcel->getActiveSheet()->SetCellValue($a, $v['uname']);
			$objPHPExcel->getActiveSheet()->SetCellValue($b, $cates[$v['mtype']]);
			$objPHPExcel->getActiveSheet()->SetCellValue($c, date('Y-m-d',$v['read_time']));
			$objPHPExcel->getActiveSheet()->SetCellValue($d, $v['money']);
			$objPHPExcel->getActiveSheet()->SetCellValue($e, $v['grid']);
			$objPHPExcel->getActiveSheet()->SetCellValue($f, $read);
			$objPHPExcel->getActiveSheet()->SetCellValue($g, $over);
			$objPHPExcel->getActiveSheet()->SetCellValue($h, $v['openid']);
		}
		

		
		 
		// Rename sheet
		$objPHPExcel->getActiveSheet()->setTitle('Csat');
		 		   
		// Save Excel 2007 file
		//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
		  
		 $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
		 $objWriter->save(str_replace('.php', '.xls', __FILE__));
		 $time= date('Y-m-d').'output';
		 header("Pragma: public");
		 header("Expires: 0");
		 header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
		 header("Content-Type:application/force-download");
		 header("Content-Type:application/vnd.ms-execl");
		 header("Content-Type:application/octet-stream");
		 header("Content-Type:application/download");
		 header("Content-Disposition:attachment;filename={$time}.xls");
		 header("Content-Transfer-Encoding:binary");
		 $objWriter->save("php://output");

	}
}

?>